﻿using Newtonsoft.Json;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.ServiceProcess;

namespace f2poolWindowsService
{
    public partial class Service1 : ServiceBase
    {
        private System.Timers.Timer timer1;  //计时器
        protected RedisClient Redis;//redis服务IP和端口
        private const string RedisKeyHead = "TomNetRedisCache_CalculationCloud_";
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            this.timer1.Enabled = false;

            Redis = new RedisClient("114.215.42.18", 6379, "abc123@", 1);//redis服务IP和端口
            timer1 = new System.Timers.Timer();

            timer1.Interval = 600000;  //设置计时器事件间隔执行时间  10分钟

            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);

            timer1.Enabled = true;
        }

        protected override void OnStop()
        {
            this.timer1.Enabled = false;
            Redis.Dispose();
        }
        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            var BType = Redis.Get<string>(RedisKeyHead + "BType");
            var btypes = BType.Split(',');
            foreach (var item in btypes)
            {
                var d = GetData(item);

                var profitDayYield = d.data.price * d.data.profit_per_t;   //预计日产量
                var unit = d.data.profit_per_hash;//预计日常量 单位
                var lineData = d.data.chart_data;
                //TomNetRedisCache_CalculationCloud
                Redis.Set<string>(RedisKeyHead + item + "_profitDayYield", profitDayYield.ToString());
                Redis.Set<string>(RedisKeyHead + item + "_unit", unit.ToString());
                Redis.Set<string>(RedisKeyHead + item + "_lineData", JsonConvert.SerializeObject(lineData));
            } 

        }
        public static F2poolDataModel GetData(string Btype = "btc")
        {
            using (HttpClient httpClient = new HttpClient())
            {
                var url = new Uri("https://www.f2pool.com/coins-chart");
                var body = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "currency_code", Btype},
{ "history_days", "30d"},
{ "interval", "60m"},
});
                var response = httpClient.PostAsync(url, body).Result;
                var data = response.Content.ReadAsStringAsync().Result;
                var d = JsonConvert.DeserializeObject<F2poolDataModel>(data);
                return d;
            }

        }
    }
}
